/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kedacom.demo.sigar.util;

import java.lang.management.ManagementFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
import org.hyperic.sigar.jmx.SigarRegistry;

/**
 *
 * @author xiaojinghai
 */
public class SigarUtil {

    private static final Logger logger = Logger.getLogger(SigarUtil.class.getName());
    private static Sigar instance;
    private static SigarProxy sigarProxyCached;
    private static int intProxyCachedExpire = 1 * 1000; //1 seconds

    static {
        instance = new Sigar();
        logger.info("Sigar API Version:" + Sigar.VERSION_STRING);
        logger.info("Sigar Native Version:" + Sigar.NATIVE_VERSION_STRING);
        sigarProxyCached = SigarProxyCache.newInstance(instance, intProxyCachedExpire);
    }

    public static Sigar getSigarInstance() {
        return instance;
    }

    public static SigarProxy getSigarProxyCache() {
        return sigarProxyCached;
    }

    public static double getLoadAverage() {
        double[] value = {-1};
        try {
            value = sigarProxyCached.getLoadAverage();
        }
        catch (SigarException ex) {
            logger.log(Level.WARNING, "该平台不支持此方法", ex);
        }

        return value[0];
    }

    public static void registSigarMBeans() {
        MBeanServer server;
        server = ManagementFactory.getPlatformMBeanServer();
        SigarRegistry rgy = new SigarRegistry();
        try {
            ObjectName name = new ObjectName(rgy.getObjectName());
            if (!server.isRegistered(name)) {
                server.registerMBean(rgy, name);
            }
        }
        catch (Exception ex) {
            logger.log(Level.WARNING, "SigarJMXBeans注册失败", ex);
        }

    }
}
